package com.suo.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AdminFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        String[] urls = {
                "/css/",
                "/admin/",
                "/fonts/",
                "/image/",
                "/image_big/",
                "/image_comm/",
                "/imagecanshu/",
                "/imagedetail/",
                "/images/",
                "/js/",
                "/WEB-INF/",
                "/admin/login.jsp"
        };

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String url = httpServletRequest.getRequestURL().toString();

        for(String s : urls) {
            if(url.contains(s)){
                chain.doFilter(request,response);
                return;
            }
        }

        HttpSession session = httpServletRequest.getSession();

        Object admin = session.getAttribute("admin");


        if (admin != null) {
            chain.doFilter(request,response);
        }
        else {
            httpServletResponse.sendRedirect("admin/login.jsp");
        }
    }
}
